<template>
  <div class="item">
    <div class="title">
      <div class="title-left">{{ titleTextCpt }}</div>
      <div class="title-right">
        <button :disabled="isDisMoveUp" @click="handleMove('up')">上移</button>
        <button :disabled="isDisMoveDown" @click="handleMove('down')">下移</button>
        <button @click="handleDel">删除</button>
      </div>
    </div>

    <div class="content">
      <template v-if="props.productDetail.type == 1">
        <div class="big-img">
          <img :src="commonStore.img_domain + formData.bigImage[0]" />
        </div>
      </template>

      <template v-if="props.productDetail.type == 2">
        <div class="small-img">
          <template v-for="(item, index) in formData.smallImages" :key="item">
            <div class="img-item">
              <img class="img" :src="commonStore.img_domain + item" />
              <img class="close" src="@/assets/icons/close.png" @click="handleDelImg(index)" />
            </div>
          </template>
          <template v-if="formData.smallImages.length <= 8">
            <nut-uploader url="#" accept="image/*" :before-upload="beforeUpload"></nut-uploader
          ></template>
        </div>
      </template>

      <template v-if="props.productDetail.type == 3">
        <nut-textarea v-model="formData.text" placeholder="请输入文字介绍" autosize />
      </template>

      <!-- <template v-if="props.productDetail.type == 4">
        <div class="video">视频</div>
      </template> -->
    </div>
  </div>

  <del-dialog ref="delDialogRef" @confirm="handleDelConfirm"></del-dialog>
</template>

<script lang="ts" setup>
  import DelDialog from "@/components/Dialog/index.vue"
  import { computed, ref, onActivated } from "vue"
  import useCommonStore from "@/store/common"
  import { Toast } from "@nutui/nutui"
  import { uploadImgApi, getOSTokenApi } from "@/api/addstart"
  import { getClient, ossPath } from "@/utils/alioss"

  // - props
  interface IProps {
    productDetail: any
    isDisMoveUp: boolean
    isDisMoveDown: boolean
  }
  const props = defineProps<IProps>()

  // - store
  const commonStore = useCommonStore()

  // - data
  const delDialogRef = ref<InstanceType<typeof DelDialog>>()
  const formData = ref<any>({
    type: props.productDetail.type,
    text: "",
    smallImages: [],
    bigImage: []
  })
  const credentials = ref<any>({
    securityToken: "",
    accessKeySecret: "",
    accessKeyId: ""
  })

  // - computed
  const titleTextCpt = computed(() => {
    switch (props.productDetail.type ?? 1) {
      case 1:
        return "大图"
      case 2:
        return "小图"
      case 3:
        return "文字"
      case 4:
        return "视频"
      default:
        break
    }
  })

  // - emits
  const emit = defineEmits(["delIntro", "moveIntro"])

  // - methods
  const handleMove = (type: string) => {
    emit("moveIntro", { type, id: props.productDetail.id })
  }
  const handleDel = () => {
    delDialogRef.value?.openDialog()
  }
  const handleDelConfirm = () => {
    emit("delIntro", props.productDetail.id)
  }
  const beforeUpload = (fileList: File[]) => {
    // uploadImg(fileList[0])
    uploadOSS(fileList[0], 'image')

    return new Promise((resolve) => {
      resolve(fileList)
    })
  }
  const handleDelImg = (index: any) => {
    formData.value.smallImages.splice(index, 1)
  }

  // ------ request
  async function uploadImg(imgfile: File) {
    const res = await uploadImgApi({ imgfile })
    if (res.code == 0) {
      const { img_key } = res.result
      formData.value.smallImages.push(img_key)
    }
  }
  // 接口：获取OSS Token
  async function getOSSToken() {
    const res = await getOSTokenApi()
    if (res.code == 0) {
      const { accessKeyId, accessKeySecret, securityToken } = res.result.credentials
      credentials.value.accessKeyId = accessKeyId
      credentials.value.accessKeySecret = accessKeySecret
      credentials.value.securityToken = securityToken
    }
  }
  async function uploadOSS(file: any, fileType: any) {
    var imgUrl = ossPath(file, fileType)
    getClient(
      credentials.value.accessKeyId,
      credentials.value.accessKeySecret,
      credentials.value.securityToken
    )
      .multipartUpload(imgUrl, file)
      .then((res: any) => {
        if (res.res.statusCode == 200) {
          var pathurl = res.name.replace("image/", "")
          formData.value.smallImages.push(pathurl)
        }
      })
  }

  function init() {
    if (props.productDetail.bigImage) {
      formData.value.bigImage.push(props.productDetail.bigImage)
    }
    if (props.productDetail.smallImage) {
      const index = formData.value.smallImages.findIndex(
        (item: any) => item == props.productDetail.smallImage
      )
      if (index == -1) {
        formData.value.smallImages.push(props.productDetail.smallImage)
      }
    }
    getOSSToken()
  }
  init()

  const submit = () => {
    return { ...formData.value }
  }
  defineExpose({ submit })
</script>

<style lang="scss" scoped>
  .item {
    .title {
      display: flex;
      justify-content: center;
      align-items: center;
      height: 114px;

      .title-left {
        font-size: 28px;
        font-family: PingFang-SC-Regular, PingFang-SC;
        font-weight: 400;
        color: #000000;
        word-break: keep-all;
      }

      .title-right {
        display: flex;
        justify-content: flex-end;
        align-items: center;
        position: relative;
        width: 100%;
        height: 100%;

        button {
          background: none;
          width: 73px;
          height: 40px;
          border-radius: 6px;
          border: 1px solid #a7b3a5;
          font-size: 24px;
          font-family: PingFang-SC-Regular, PingFang-SC;
          font-weight: 400;
          color: #000000;
          margin-left: 20px;
        }

        button:disabled {
          opacity: 0.5;
        }
      }
    }

    .content {
      min-height: 200px;

      .big-img {
        box-sizing: border-box;
        padding: 0 10px;

        img {
          display: block;
          width: 100%;
        }
      }
      .small-img {
        display: flex;
        flex-wrap: wrap;
        .img-item {
          position: relative;
          display: block;
          width: 30%;
          height: 210px;
          margin: 0 20px 20px 0;

          .img {
            display: block;
            width: 100%;
            height: 210px;
          }

          .close {
            position: absolute;
            top: -8px;
            right: -8px;
            width: 36px;
          }
        }
      }
      .video {
      }
    }

    :deep(.nut-textarea) {
      height: auto !important;
    }
  }
</style>
